package com.dsiab.manageService.jwt;

import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@ConfigurationProperties(prefix = "jwt")
@Slf4j
public class JwtTokenUtil {
    private static final long  expiration = 1000 * 60 * 60 * 8 ;
    private String header = "Authorization";
    private String secretKey = "ye874kte5874zsdal54FKpqa8425rceSy";

    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims= new HashMap<>();
        claims.put("sub",userDetails.getUsername());
        claims.put("created",new Date());
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+ expiration))
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }
    public String getUsernameFromToken(String token){
        return getClaimsFromToken(token).getSubject();
    }
    private  Claims getClaimsFromToken(String token){
        Claims claims =  Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
        return  claims;
    }
    public String getToken (HttpServletRequest httpServletRequest) {
        final String token = httpServletRequest.getHeader(header);
        if(StringUtils.hasText(token)) {
            return token;
        }
        return null;
    }
    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
            return true;
        } catch (SignatureException e) {
            log.info("Invalid JWT signature.");
            log.trace("Invalid JWT signature trace: {}", e);
        } catch (MalformedJwtException e) {
            log.info("Invalid JWT token.");
            log.trace("Invalid JWT token trace: {}", e);
        } catch (ExpiredJwtException e) {
            log.info("Expired JWT token.");
            log.trace("Expired JWT token trace: {}", e);
        } catch (UnsupportedJwtException e) {
            log.info("Unsupported JWT token.");
            log.trace("Unsupported JWT token trace: {}", e);
        } catch (IllegalArgumentException e) {
            log.info("JWT token compact of handler are invalid.");
            log.trace("JWT token compact of handler are invalid trace: {}", e);
        }
        return false;
    }
}
